<template>
  <view class="content">
    <view class="wrapperBox" style="position: relative;width: 100vw;height: 100vh;z-index: 1;">
      <view style="width: 120vw;height: 120vh;top: -10vh;left: -10vw;position: absolute;" id="wrapper"></view>
    </view>
    <!-- 加载提示 -->
    <view v-if="loading" class="loading-mask">
      <view class="loading-spinner"></view>
      <text class="loading-text">地图加载中...</text>
    </view>
  </view>
</template>

<script>
// 修复后的区域数据（包含完整的样式配置）
const AREA_DATA = [
  {
    name: 'agriculture',
    markerList: [
      [113.460787, 22.22839, 113.460801, 22.227644, 113.45945, 22.227582, 113.459423, 22.228346]
    ],
    style: {
      polygon: {
        color: 'rgba(35, 181, 29, 0.6)',
        showBorder: true,
        borderColor: 'rgba(35, 181, 29, 1)',
        borderWidth: 2
      }
    }
  },
  {
    name: 'property',
    markerList: [
      [113.475984, 22.253749, 113.477205, 22.254632, 113.477805, 22.253963, 113.477209, 22.252339]
    ],
    style: {
      polygon: {
        color: 'rgba(70, 207, 209, 0.6)',
        showBorder: true,
        borderColor: 'rgba(70, 207, 209, 1)',
        borderWidth: 2
      }
    }
  }
  // 其他区域...
];

export default {
  data() {
    return {
      key: 'EBABZ-ILNLQ-CXO5V-4IEDG-V5GPO-2HBIE',
      currentPosition: {
        longitude: 111.75000,
        latitude: 40.84236
      },
      loading: true,
      mapObj: null,
      infoWindow: null,
      isShowText: false,
      iconItem: [...AREA_DATA] // 使用修复后的数据
    }
  },
  onLoad() {
    this.initMapSystem();
  },
  methods: {
    async initMapSystem() {
      try {
        // 1. 尝试获取定位
        await this.getCurrentLocation();
        
        // 2. H5端加载地图
        // #ifdef H5
        await this.loadMapScript();
        this.initMap();
        // #endif
        
      } catch (error) {
        console.error('初始化失败:', error);
        uni.showToast({
          title: '地图初始化失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    getCurrentLocation() {
      return new Promise((resolve) => {
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            if (this.validateCoordinate(res.latitude, res.longitude)) {
              this.currentPosition = {
                longitude: res.longitude,
                latitude: res.latitude
              };
            }
            resolve();
          },
          fail: (err) => {
            console.warn('定位失败:', err);
            resolve(); // 继续使用默认坐标
          }
        });
      });
    },
    
    validateCoordinate(lat, lng) {
      return Math.abs(lat) <= 90 && Math.abs(lng) <= 180;
    },
    
    loadMapScript() {
      return new Promise((resolve, reject) => {
        if (window.TMap) return resolve();
        
        const script = document.createElement('script');
        script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${this.key}`;
        script.onload = () => {
          window.TMap ? resolve() : reject('TMap未加载');
        };
        script.onerror = reject;
        document.body.appendChild(script);
      });
    },
    
    initMap() {
      this.mapObj = new TMap.Map("wrapper", {
        center: new TMap.LatLng(
          this.currentPosition.latitude,
          this.currentPosition.longitude
        ),
        zoom: 14,
        mapStyleId: 'style1',
        baseMap: {
          type: 'vector',
          features: ['base', 'point']
        }
      });
      
      this.initInfoWindow();
      this.setupMapEvents();
      this.renderAreas();
    },
    
    initInfoWindow() {
      this.infoWindow = new TMap.InfoWindow({
        map: this.mapObj,
        enableCustom: true,
        position: new TMap.LatLng(
          this.currentPosition.latitude,
          this.currentPosition.longitude
        ),
        offset: { y: 30, x: 230 },
        content: `<div style="width:379px;height:134px;padding:16px;"></div>`
      });
    },
    
    setupMapEvents() {
      this.mapObj.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM);
      this.mapObj.on("click", () => {
        this.isShowText = !this.isShowText;
        if (!this.isShowText) {
          this.infoWindow.close();
        }
      });
    },
    
    // 修复后的区域渲染方法
    renderAreas() {
      this.iconItem.forEach(item => {
        try {
          // 验证数据格式
          if (!Array.isArray(item.markerList) || !item.style || !item.style.polygon) {
            console.warn('区域数据格式错误:', item.name);
            return;
          }
          
          // 构建路径
          const path = item.markerList[0].reduce((acc, _, i, arr) => {
            if (i % 2 === 0 && i+1 < arr.length) {
              const lng = arr[i];
              const lat = arr[i+1];
              if (this.validateCoordinate(lat, lng)) {
                acc.push(new TMap.LatLng(lat, lng));
              }
            }
            return acc;
          }, []);
          
          // 确保有有效的路径点
          if (path.length < 3) {
            console.warn('区域点数量不足:', item.name);
            return;
          }
          
          // 创建多边形（使用完整的样式配置）
          new TMap.MultiPolygon({
            map: this.mapObj,
            styles: {
              // 使用item.style中的完整配置
              polygon: new TMap.PolygonStyle({
                color: item.style.polygon.color,
                showBorder: item.style.polygon.showBorder,
                borderColor: item.style.polygon.borderColor,
                borderWidth: item.style.polygon.borderWidth || 2
              })
            },
            geometries: [{
              id: item.name,
              styleId: 'polygon',
              paths: [path]
            }]
          });
          
        } catch (error) {
          console.error(`渲染区域${item.name}失败:`, error);
        }
      });
    }
  }
}
</script>

<style scoped>
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255,255,255,0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #07c160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  margin-top: 15px;
  color: #666;
  font-size: 14px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>